package cn.getech.data.development.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;


@ConfigurationProperties(prefix = "data-development.rsa")
@Component
public class SecurityUtil {
    // private String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJZHIUC9r36EOUIBuX1HEUeTxBoVV4Os+eCYXQkvd5Ulbix6LtNilvlV3qSbBpUlff/zGkPmVOzjj+OQDVF71A82YC5wR/28pmhAldb0sCdGnJRrZBzuAJQxzip5dTx7kotL6K80kXCB+BiRYAdVjFTUVUJTG6yblS8yMp1XvsTwIDAQAB";
    private String publicKey;
    private String privateKey;

    public String getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public  Map<String,String> genKeyPair() throws NoSuchAlgorithmException {
        Map<String,String> keyMap=new HashMap<>();
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        keyMap.put("publicKey",publicKeyString);
        keyMap.put("privateKey",privateKeyString);
        return  keyMap;
    }

    /**
     * RSA公钥加密
     *
     * @param str 加密字符串
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public  String encrypt( String str ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public  String decrypt(String str) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }


//    public static void main(String[] args) throws Exception {
//        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIlkchQL2vfoQ5QgG5fUcRR5PEGhVXg6z54JhdCS93lSVuLHou02KW+VXepJsGlSV9//MaQ+ZU7OOP45ANUXvUDzZgLnBH/bymaECV1vSwJ0aclGtkHO4AlDHOKnl1PHuSi0vorzSRcIH4GJFgB1WMVNRVQlMbrJuVLzIynVe+xPAgMBAAECgYA5bl5tWMNQa6uMCJvgLLKUL1VrzcfPeS3+Tta76CNAeJXPOEo3xDMv7I0UeXcfn4cSIDedA2QPvA6A3k0lxkWaecxHx3XtO1o7EYgNwl36zaa3OdriS3++LlKpuMk8IOwKMiDYM+dqb85dJnQlvwBbIslTf3HjA957UFlRYRawEQJBANVPmCC8BweoRC4WYOk2nI7UjQHHx6vvQQ+8MKVjxC9lJglC2MJOh+BjcAHr0Y7BYviBvLiqKn7rxwT9OVXmCQkCQQCk417cxPTgvDAmR8TQzYtdCqm4H56uKJnxhs2LHxP2VcG9pifVwjdlejdd3hF0OEDINHunRsptpRnJFLg2BdiXAkEAhroD+sDnq8Vycq19vi7ZCTlkajh1e7ncnQSesQdnVQwMzxKid29EUMxdZUk9jW3FhfHjcbtApfNjO1p4yTFGiQJAJEKL/eiiITnBLOnjcjeBSjiqEf+CGbJ8CA0o7ksrTKSXMmlzoSJQpFQ4EMBg/jnQpTZFawe6RFpmTT3tNJQciQJAMIU50ZnZDzUWUka70HnomJxe3HuirGfv706nzcg2QMD1WQQ5Rlm1FjpojwHTG8Pcf3tpEUQbVGqLZYz53FT0ZQ==";
//        String passw = "JdpZvaWc6xmuZsQakvepBp+kyh606PM+wByyghyAdRPvPuNR42fE6/MjgyAkJCEJohtSdJiK2cg9JdmstpsO+TLQzIm6Sk9rCs0zh625QGJ855Usn7dD2WnEGubITWA2ZPlJDcbuA7loRmvGKSRyBOtfKAPUkTu8+TIsNsz+xOg=";
//        SecurityUtil securityUtil = new SecurityUtil();
//        securityUtil.setPrivateKey(privateKey);
//        String decrypt = securityUtil.decrypt(passw);
//        System.err.println(decrypt);
//
//    }

    
}
